<?php

/**
 * 翼支付插件
 *
 * @author libaoling
 * @time 2014-8-28
 */
class bestpay
{
	private $_payment = array(
	'merchant_id' => '02440103010621000',
	'api_url' => 'https://webpaywg.bestpay.com.cn/payWeb.do',
	'key' => '5AC0AC329DE7CF1881613FFC76490BE16842B646F625000D'
	);

	/**
     * 生成支付代码
     * @param   array   $order      订单信息
     * @param   array   $payment    支付方式信息
     */
	public function get_code($order)
	{
		$charset = 'UTF-8';

		/* 总金额 */
		/* 商品价格（包含运费），以分为单位 */
		$total_fee = floatval($order['trans_amount']) * 100;

		$parameter = array(
		'MERCHANTID' => $this->_payment['merchant_id'],
		'ORDERSEQ' => $order['trans_code'],  //订单号
		'ORDERREQTRANSEQ' => $order['order_trans_seq'],  //订单请求交易流水号
		'ORDERDATE' => date('Ymd'),  //订单日期
		'ORDERAMOUNT' => $total_fee,  //订单总金额
		'PRODUCTAMOUNT'  => $total_fee,  //产品金额
		'ATTACHAMOUNT'  => 0,  //附加金额
		'CURTYPE' => 'RMB',  //币种
		'ENCODETYPE' => '1',  //加密方式
		'MERCHANTURL' => $order['return_url'],  //前台返回地址
		'BACKMERCHANTURL' => $order['notify_url'],  //后台返回地址
		'BUSICODE' => '0001',  //业务标识
		'PRODUCTID' => '08',  //业务标识
		'CUSTOMERID' => $order['buyer_name'],  //客户标识
		'PRODUCTDESC' => $order['body'],  //产品描述
		'MAC' => $this->_make_mac($order),  //MAC校验域
		'CLIENTIP' => real_ip(),  //客户端IP
		);

		$html = '';
		$html .= '<html>'."\n";
		$html .= '<head>'."\n";
		$html .= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'."\n";
		$html .= '<title>翼支付支付，正在跳转...</title>'."\n";
		$html .= '</head>'."\n";
	    $html .= '<body onLoad="document.bestpay.submit();">'."\n";

		$form_content = '';
		foreach ($parameter AS $k => $v)
		{
			$form_content .= "<input type='hidden' name='{$k}' value='".$v."'>\n";
		}

		$html .= "<form name='bestpay' action='{$this->_payment['api_url']}' method='post' >\n";
		$html .= $form_content;
		$html .= "<input style='display:none;' type='submit' value='确定支付' />\n";
		$html .= "</form>\n";
		$html .= "</body>\n";
		$html .= "</html>\n";

		return $html;

	}

	/**
     * 响应操作
     */
	function respond()
	{
		if (!empty($_POST))
		{
			foreach($_POST as $key => $data)
			{
				$_GET[$key] = $data;
                //用于前台显示的金额
				/*if($key == 'ORDERAMOUNT')
				$_GET['total_fee'] = $data/100;*/
			}
		}

		if(isset($_GET['SIGN']) && $_GET['SIGN'])
		{
			if ($this->_get_sign() == strtoupper($_GET['SIGN']))
			return $this->_getStatus();  //判断支付是否成功
			else
			return -1;//签名不对，这里不写入错误日志，防止同步跳转，别人恶意攻击，写入文件，影响服务器
		}else
		return -2;

	}

	/**
    * 获取外部交易号
    */
	public function get_out_trade_no()
	{
		return $_REQUEST['ORDERSEQ'];
	}

	/**
     * 检查金额是否相符
     * @param total_price,数据库中的订单金额
     * @return  void
     */
	public function check_total_fee($total_price)
	{
		$order_amount = $_REQUEST['ORDERAMOUNT']/100;
		if($total_price == $order_amount)
		return true;
		else
		return false;
	}
	
	/**
     * 获取订单金额
     */
	public function get_total_fee()
	{
		$order_amount = $_REQUEST['ORDERAMOUNT']/100;
		
		return $order_amount;
	}

	/**
     *    错误消息
     */
	public function error_message($num)
	{
		switch ($num)
		{
			case -1:
				$msg = '签名不对';
				break;
			case -2:
				$msg = '参数不正确，未提供sign';
				break;
			case -3:
				$msg = '支付结果未知';
				break;
			case -4:
				$msg = '支付失败';
				break;
		}
		return $msg;
	}

	/**
     *    将验证结果反馈给网关
     *
     *    @author    Garbin
     *    @param     bool   $result
     *    @return    void
     */
	public function verify_result($result)
	{
		$bool = isset($_GET['RETNCODE']) && $_GET['RETNCODE'] && isset($_GET['UPTRANSEQ']) && $_GET['UPTRANSEQ'];
		if ($result && $bool)
		{
			echo "UPTRANSEQ_{$_GET['UPTRANSEQ']}";
		}
		else
		echo 'fail';
	}

	/*
	* 生成MAC校验域
	*/
	private function _make_mac($order)
	{
		$str = "MERCHANTID=" . $this->_payment['merchant_id'] .
		"&ORDERSEQ=" . $order['trans_code'] .
		"&ORDERDATE=" . date('Ymd') .
		"&ORDERAMOUNT=" . floatval($order['trans_amount']) * 100 .
		"&CLIENTIP=" . real_ip() .
		'&KEY=' . $this->_payment['key'];
		return strtoupper(md5($str));
	}

	/*
	* 数字签名
	*/
	private function _get_sign()
	{
		if(empty($_GET))
		return '';

		$params = $_GET;
		$str = "UPTRANSEQ=" . $params['UPTRANSEQ'] .
		"&MERCHANTID=" . $this->_payment['merchant_id'] .
		"&ORDERID=" . $params['ORDERSEQ'] .
		"&PAYMENT=" . $params['ORDERAMOUNT'] .
		"&RETNCODE=" . $params['RETNCODE'] .
		'&RETNINFO=' . $params['RETNINFO'] .
		'&PAYDATE=' . $params['TRANDATE'] .
		'&KEY=' . $this->_payment['key'];
		return strtoupper(md5($str));
	}

	/*
	* 比对结果码为，判断支付是否成功
	*/
	private function _getStatus()
	{
		if(isset($_GET['act']) && $_GET['act'])
		return 1;
		else
		{
			if(isset($_GET['RETNCODE']) && $_GET['RETNCODE'])
			{
				if($_GET['RETNCODE'] == '0000')
				return 1;
				else
				return -4;
			}
			else
			return -3;
		}
	}
	/**
     *    支付费率
     *    @param  money 订单总额
     */
	function get_pay_rate($money)
	{
		
		$pay_rate = 0.0025;
		return $pay_rate;

	}


}
